package com.gmrz.uaf.servlet.v1.handler;

import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.common.GuiceUtil;
import com.gmrz.uaf.protocol.v1.json.UAFSchemaBuilder;
import com.gmrz.uaf.protocol.v1.processor.UAFQueryRegListProcessor;
import com.gmrz.uaf.protocol.v1.schema.AuthenticatorRegList;
import com.gmrz.uaf.server.ServerContext;
import com.gmrz.uaf.servlet.v1.request.ReceiveReqPayload;
import com.gmrz.uaf.servlet.v1.response.FidoRespPayload;
import com.gmrz.uaf.servlet.v1.validation.PayloadValidationException;
import com.gmrz.uaf.servlet.v1.validation.RestValidator;
import com.gmrz.util.Strings;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @PACKAGE_NAME: com.gmrz.uaf.servlet.v1.handler
 * @ClassName: UAFQueryRegListHandler
 * @Description:  根据用户名、渠道号等查询用户注册信息 handler
 * @Date: 2020-04-29 14:24
 * @Author: liyl@gmrz-bj.com
 **/
public class UAFQueryRegListHandler extends UAFBaseHandler  {

    private static final Logger LOG = LogManager.getLogger(UAFQueryRegListHandler.class);


    /**
     * @param request
     * {
          "context":{
            "userName":"test-0023",
            "appID": "1103"
           }
        }
     *
     * @return
     * {
    "authenticators": [
        {
        "aaid": "004A#9999",
        "aliasName": "X33",
        "appID": "1103",
        "authId": "07ff0d7dc1a64fac966c18d235ffbb9b",
        "authType": "00",
        "custNo": "test-0023",
        "deviceID": "HWxkVQWERTYUIOPASDFGHJKLZXCVBNMQWERTYUIOPASDFGHJKL10",
        "deviceName": "vivoX3356",
        "deviceType": "vivio",
        "keyID": "whD1WOpquqS6zjE6ALEO77Wq8mnv2RadCjXz45sVDNk",
        "osType": "android",
        "osVersion": "666",
        "transType": "00",
        "userName": "776b49553a608e23bee4300259946e19011b1904"
        }
    ],
    "description": "OK",
    "statusCode": 1200
    }
     */
    public String queryRegListByUserNameAndTenantID(String request){
        LOG.info("[/reg/list][begin]");
        ServerContext.getServerContext().getFidoLog().setRequest(request);
        FidoRespPayload<List<AuthenticatorRegList>> respPayload = new FidoRespPayload<List<AuthenticatorRegList>>();
        String response = null;

        try {

            Gson gson = UAFSchemaBuilder.getGson();
            Type reqType = new TypeToken<ReceiveReqPayload<AuthenticatorRegList>>() {  }.getType();

            // 将请求串转为对象
            ReceiveReqPayload<AuthenticatorRegList> reqPayload =gson.fromJson(request, reqType);

            // 记录日志
            logRequest(request, null, reqPayload.getContext().getUserName(),
                    reqPayload.getContext().getAppID(), reqPayload.getContext().getAuthType(),
                    reqPayload.getContext().getTransType(), Constants.Method.REG_LISYT);

            // 校验参数
            validate(reqPayload);

            UAFQueryRegListProcessor processor = GuiceUtil.getProcessorInjector().
                    getInstance(UAFQueryRegListProcessor.class);

            // hash 用户名，使用 SHA-1 摘要算法对用户信息进行摘要计算，然后在将摘要转为16进制字符串
            String hashedUserName = generateHashedUserName(reqPayload.getContext().getUserName(),
                    reqPayload.getContext().getRf1(), reqPayload.getContext().getRf2());

            // 业务逻辑
            List<AuthenticatorRegList> authenticators = processor.queryRegListByUserNameAndTenantID( hashedUserName,
                    reqPayload.getContext().getAppID(), reqPayload.getContext().getTransType(),
                    reqPayload.getContext().getAuthType());

            // 构造响应
            respPayload.setStatusCode(1200);
            respPayload.setDescription("OK");
            respPayload.setAuthenticators(authenticators);
            return gson.toJson(respPayload);

        }catch (Exception ex){
            LOG.error(ex);
            response = buildFidoRespFromException(respPayload, ex);
        }

        LOG.info("[/reg/list][end]");
        return response;
    }



    void validate(ReceiveReqPayload<AuthenticatorRegList> reqPayload) throws PayloadValidationException {
        if ((null == reqPayload) || (null == reqPayload.getContext())) {
            throw new PayloadValidationException("context", RestValidator.VALIDATION_ERROR.EMPTY);
        }
        RestValidator.validate("userName", reqPayload.getContext().getUserName());
        RestValidator.validate("appID", reqPayload.getContext().getAppID());
        if (Strings.isNotBlank(reqPayload.getContext().getTransType())){
            RestValidator.validate("transType", reqPayload.getContext().getTransType());
        }
        if (Strings.isNotBlank(reqPayload.getContext().getAuthType())){
            RestValidator.validate("authType", reqPayload.getContext().getAuthType());
        }
        if(Strings.isNotBlank(reqPayload.getContext().getRf1())){
            RestValidator.validate("rf1", reqPayload.getContext().getRf1());
        }
        if(Strings.isNotBlank(reqPayload.getContext().getRf2())){
            RestValidator.validate("rf2", reqPayload.getContext().getRf2());
        }

    }
}
